package com.lagou.base;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;

public class BaseServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //String methodName = req.getParameter("methodName");
        String methodName = null;

        String header = req.getHeader("Content-Type");
        if ("application/json;charset=utf-8".equals(header)) {

            String postJSON = getPostJSON(req);

            Map<String,Object> map = JSON.parseObject(postJSON, Map.class);

            methodName = (String) map.get("methodName");

            req.setAttribute("map",map);


        }else {
            methodName = req.getParameter("methodName");
        }
        if (methodName != null) {
            //通过反射优化代码，提升代码的可维护性
            try {
                Class c = this.getClass();

                Method method = c.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);

                method.invoke(this, req, resp);

            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("请求的功能不存在！");
            }

        }
    }

    

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }

    public String getPostJSON(HttpServletRequest request) {

        try {
            BufferedReader reader = request.getReader();

            StringBuffer sb = new StringBuffer();

            String line = null;

            while ((line = reader.readLine()) != null) {

                sb.append(line);

            }

            return sb.toString();

        } catch (IOException e) {

            e.printStackTrace();
            return null;

        }

    }}


